<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Schema;

class AddOperateLog
{
    /**
     * 添加操作日志
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth('admin')->user()->id == 1){
            return $next($request);
        }
        if (Schema::hasTable('operate_log')) { 
            $uri = $request->path();
            $path = DB::table('auth')->where('url',$uri)->value('path');
            if (!$path) {
                return $next($request);
            }
            $ids = explode('-',$path);
            $auths = DB::table('auth')->where('auth_name','!=','')->pluck('auth_name','id');
            $auth_name = '';
            foreach ($ids as $id) {
                $auth_name .= data_get($auths,$id,'').'-';
            }
            $auth_name = trim($auth_name,'-');
            $ip = $request->ip();
            DB::table('operate_log')->insert([
                'ip'         => $ip,
                'addr'       => \App\Libs\Helper::getAddrByIp($ip),
                'realname'   => auth('admin')->user()->realname,
                'auth_name'  => $auth_name,
                'url'        => $request->fullUrl(),
            ]);
        }
        //继续后续的请求
        return $next($request);
    }
}